﻿using System;

namespace VincentUtil.Ntp
{
    public class NtpResponseMessage : NtpMessage
    {
        /// <summary>
        /// 接收：服务器最后一次更新时钟的时间
        /// </summary>
        public DateTime ReferenceTime;

        /// <summary>
        /// 接收：接收到请求的时间
        /// </summary>
        public DateTime ReceiveTime;

        public NtpResponseMessage(DateTime originTime, DateTime transmitTime,
            DateTime referenceTime, DateTime receiveTime) : base(originTime, transmitTime)
        {
            ReferenceTime = referenceTime;
            ReceiveTime = receiveTime;
        }

        public NtpResponseMessage() : base(DateTime.MinValue, DateTime.MinValue)
        {
            ReferenceTime = DateTime.MinValue;
            ReceiveTime = DateTime.MinValue;
        }


        public override byte[] BuildNTPBytes()
        {
            byte[] ntpData = base.BuildNTPBytes();
            ntpData[0] = 0x24;// LI = 0, Version = 3 (IPv4 only), Mode = 4 (Server)
            NtpUtil.TryWriteNtpTime(ntpData, _referenceTimeIndex, ReferenceTime);
            NtpUtil.TryWriteNtpTime(ntpData, _receiveTimeIndex, ReceiveTime);
            return ntpData;
        }

        public static bool TryResolve(byte[] ntpData, out NtpResponseMessage message)
        {
            message = new NtpResponseMessage();
            if (ntpData.Length < 48 || ntpData[0] != 0x24) return false;
            if (!NtpUtil.TryResolveNtpTime(ntpData, _originTimeIndex, out DateTime origionTime))
                return false;
            if (!NtpUtil.TryResolveNtpTime(ntpData, _transmitTimeIndex, out DateTime transmitTime))
                return false;
            if (!NtpUtil.TryResolveNtpTime(ntpData, _receiveTimeIndex, out DateTime receiveTime))
                return false;
            if (!NtpUtil.TryResolveNtpTime(ntpData, _referenceTimeIndex, out DateTime referenceTime))
                return false;
            message = new NtpResponseMessage(origionTime, transmitTime, referenceTime, receiveTime);
            return true;
        }
    }
}
